package com.zkingsoft.web.action;

import com.matrix.core.pojo.AjaxResult;
import com.matrix.core.pojo.PaginationVO;
import com.matrix.core.tools.*;
import com.zkingsoft.common.bean.SysUsers;
import com.zkingsoft.common.constance.AppConstance;
import com.zkingsoft.common.dao.SysUsersDao;
import com.zkingsoft.web.ArticleVo;
import com.zkingsoft.web.bean.WebArticle;
import com.zkingsoft.web.bean.WebArticleType;
import com.zkingsoft.web.bean.WebMsg;
import com.zkingsoft.web.service.WebAdService;
import com.zkingsoft.web.service.WebArticleService;
import com.zkingsoft.web.service.WebArticleTypeService;
import com.zkingsoft.web.service.WebMsgService;
import com.zkingsoft.web.tool.SystemConstance;
import com.zkingsoft.web.tool.Tools;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
@RequestMapping(value = "visitorResource")
public class VisitorResourceController {

    public  static  Map<String,String> validataMap=new HashMap<>();

    @Autowired
    WebAdService adService;

    @Autowired
    WebArticleService webArticleService;

    @Autowired
    WebArticleTypeService artTypeService;

    @Autowired
    WebMsgService webMsgService;

    @Autowired
    SysUsersDao sysUsersDao;


    /**
     * 根据codes 查询code的值
     */
    @RequestMapping(value = "/selectAdByCodes")
    public @ResponseBody
    AjaxResult selectAdByCodes(String codes) {
        AjaxResult result = new AjaxResult(AjaxResult.STATUS_SUCCESS, adService.selectAdByCodes(codes));
        return result;
    }


    /**
     * 根据栏目code 查询code的值
     */
    @RequestMapping(value = "/findAdByCloCode")
    public @ResponseBody
    AjaxResult findAdByCloCode(String cloCode) {
        AjaxResult result = new AjaxResult(AjaxResult.STATUS_SUCCESS, adService.findAdByCloCode(cloCode));
        return result;
    }


    /**
     * 根据文章分类code，分页查询文章
     */
    @RequestMapping(value = "/selectArticle")
    public @ResponseBody
    AjaxResult selectArticle(ArticleVo articleVo) {
        PaginationVO pageVo = new PaginationVO();
        BeanUtils.copyProperties(articleVo, pageVo);
        pageVo.setSort("artCreatetiem");
        pageVo.setOrder("desc");

        articleVo.setCompanyId(Tools.getCompanyId());
        articleVo.setArtIsPublish(SystemConstance.IS_Y);

        AjaxResult result = new AjaxResult();
        result.setStatus(AjaxResult.STATUS_SUCCESS);
        WebArticleType type = new WebArticleType();
        if (!StringUtils.isBlank(articleVo.getTypeCode())) {
            type.setCode(articleVo.getTypeCode());
            type.setCompanyId(Tools.getCompanyId());
            List<WebArticleType> types = artTypeService.findByModel(type);
            if (types.size() > 0) {
                articleVo.setArtTypeId(types.get(0).getArtTypeId());
                result.putInMap("cate", types.get(0));
            }
        }
        result.setRows(webArticleService.findInPage(articleVo, pageVo));
        result.setTotal(webArticleService.findTotal(articleVo));
        return result;
    }

    /**
     * 查询文章详情，需要传入文章id或者title
     */
    @RequestMapping(value = "/articleDetail")
    public @ResponseBody
    AjaxResult articleDetail(ArticleVo articleVo) {
        WebArticle art = new WebArticle();
        AjaxResult result = new AjaxResult();
        if (articleVo.getArtId() != null) {
            art = webArticleService.findById(articleVo.getArtId());
        } else if (articleVo.getArtTitle() != null) {
            art.setArtTitle(articleVo.getArtTitle());
            art = webArticleService.findByTitle(articleVo.getArtTitle());
        }

        art.setArtCount(art.getArtCount() + 1);
        webArticleService.modifyByModel(art);

        // 查询上一篇下一篇
        if (articleVo.getQueryAround() && art.getArtId() != null) {
            result.putInMap("prev", webArticleService.findAround(art.getArtId(), -1, Tools.getCompanyId()));

            result.putInMap("next", webArticleService.findAround(art.getArtId(), 1, Tools.getCompanyId()));
        }
        result.setStatus(AjaxResult.STATUS_SUCCESS);
        result.putInMap("art", art);
        return result;
    }

    @RequestMapping(value = "/register")
    public @ResponseBody
    AjaxResult register(SysUsers sysUsers) {

        if (StringUtils.isNotBlank(sysUsers.getSuTel()) && sysUsers.getSuTel().length() == 11) {
            String validCode = validataMap.get(sysUsers.getSuTel());

            LogUtil.debug("验证码比较{},{},{}",sysUsers.getSuTel(),validCode,sysUsers.getValidataCode());
            if (Objects.equals(validCode, sysUsers.getValidataCode())) {
                SysUsers sysUsersQuery=sysUsersDao.findByOpenId(sysUsers.getSuWeixinId());
                sysUsers.setSuId(sysUsersQuery.getSuId());
                sysUsersDao.updateByModel(sysUsers);
                AjaxResult result = AjaxResult.buildSuccessInstance("注册成功");

                result.putInMap("user", sysUsersDao.findByOpenId(sysUsers.getSuWeixinId()));
                validataMap.remove(sysUsers.getSuTel());
                return result;

            } else {
                return AjaxResult.buildFailInstance("验证码错误");
            }
        }
        {
            return AjaxResult.buildFailInstance("手机号码错误");
        }
    }


    @RequestMapping(value = "/getValidataCode")
    public @ResponseBody
    AjaxResult getValidataCode(@RequestBody Map param) {

        String tel = param.get("tel") + "";

        if (StringUtils.isNotBlank(tel) && tel.length() == 11) {

            String randomNum = StringUtils.getRandomNum(4);

            LogUtil.debug("手机号码{},验证码{}",tel,randomNum);

            JDSmsClient.init();
            JDSmsClient.sendValidaCode(tel, randomNum);

            validataMap.put(tel, randomNum);
            return new AjaxResult(AjaxResult.STATUS_SUCCESS, "短信发送成功" );
        } else {
            return AjaxResult.buildFailInstance("手机号码格式错误");
        }
    }


    @RequestMapping(value = "/selectArtType")
    public @ResponseBody
    AjaxResult selectArtType(WebArticleType webArticleType) {
        webArticleType.setCompanyId(Tools.getCompanyId());
        List<WebArticleType> types = artTypeService.findByModel(webArticleType);
        AjaxResult result = new AjaxResult();
        result.setStatus(AjaxResult.STATUS_SUCCESS);
        if (!types.isEmpty()) {
            result.setRows(types.get(0).getChildrenType());
            result.putInMap("self", types.get(0));
        }
        return result;
    }


    @RequestMapping(value = "/addMsg")
    public @ResponseBody
    AjaxResult addMsg(WebMsg msg) {
        msg.setCompanyId(Tools.getCompanyId());
        msg.setCreateTime(new Date());
        webMsgService.add(msg);
        return new AjaxResult(AjaxResult.STATUS_SUCCESS, "提交成功");
    }


    /**
     * 根据文章分类code，分页查询文章
     */
    @RequestMapping(value = "/selectArticleByIds")
    public @ResponseBody
    AjaxResult selectArticleByIds(String ids) {
        return AjaxResult.buildSuccessInstance(webArticleService.findByIds(ids));
    }


    /**
     * 小程序登录
     */
    @RequestMapping(value = "/login/{keys}")
    public @ResponseBody
    AjaxResult wxLogin(@PathVariable("keys") String code) throws Exception {
        AjaxResult res = new AjaxResult();
        LogUtil.info("code:{}" + code);
        if (StringUtils.isNotBlank(code)) {
            String requrl = WeChatApiTools.getXcxLoginUrl(code);
            String reslutData = HttpCurlUtil.sendGetHttp(requrl, null);
            JSONObject json = JSONObject.fromObject(reslutData);
            LogUtil.debug("微信登录获取到登录信息={}", json);
            if (json.containsKey("errcode")) {
                res.setStatus(AjaxResult.STATUS_FAIL);
                res.setInfo("自动登录失败");
                LogUtil.debug("微信登录获取到异常信息errcode");
                return res;
            }
            String openId = json.getString("openid");
            String sessionKey = json.getString("session_key");
            LogUtil.debug("openId={},sessionKey={}", openId, sessionKey);
            // 查询用户是否存在
            SysUsers users = null;
            synchronized (this) {
                users = sysUsersDao.findByOpenId(openId);
                if (users == null) {
                    // 新增用户
                    users = new SysUsers();
                    users.setSuWeiboId(sessionKey);
                    users.setSuWeixinId(openId);
                    // 设置一些基本信息
                    users.setCreateBy("system");
                    users.setUpdateBy("system");
                    users.setSuId(UUIDUtil.getRandomID());
                    users.setSuAccountStatus(AppConstance.ACCOUNT_STATUS_ACTIVATE);
                    users.setSuValid(AppConstance.RECORD_VALID);
                    users.setCompanyId(Tools.getCompanyId());
                    users.setSuUserType(AppConstance.USER_TYPE_CUSTIMER);
                    users.setSuRegisterTime(new Date());
                    sysUsersDao.insert(users);

                } else {
                    users.setSuWeiboId(sessionKey);
                    // 更新用户sessionKey
                    sysUsersDao.updateByModel(users);
                }
            }
            // 存放redis
            LogUtil.info("用户token={}", users.getSuId());
            res.putInMap("token", users.getSuId());
            res.putInMap("userInfo", users);
            res.setStatus(AjaxResult.STATUS_SUCCESS);
        } else {
            res.setStatus(AjaxResult.STATUS_FAIL);
            res.setInfo("自动登录失败");
        }
        return res;
    }



}
